<?php

namespace app\api\service;

use app\api\model\Order;
use app\api\model\ScoreShop;
use app\api\model\User;
use app\common\LogService;
use Exception;
use think\facade\Db;
use think\facade\Log;

class Pay
{

    protected $notifyUrl;
    protected $returnUrl;
    protected $tradoNo;
  
    public function __construct()
    {
        $host = Request()->host();
        $this->notifyUrl = "http://{$host}/api/pay/notifyUrl";
        //页面跳转同步通知页面路径
        $this->returnUrl = "http://{$host}/api/pay/returnUrl";
        $this->tradoNo = intval(date("YmdHis") . mt_rand(100, 999));
    }
    public function log($status, $message = '')
    {
        LogService::record(
            name: '支付',
            user_id: getUid(),
            status: $status,
            content: $message == '' ? [] : ['reason' => $message],
            user_type: 1
        );
    }
    public function initOrder()
    {
        $uid = getUid();
        $limit = Order::where('user_id', $uid)->where('create_time', '>', time() - 300)->count();
        if ($limit >= 10) {
            $this->log(0, '请再过 5 分钟后再来尝试!');
            throw new Exception('请再过 5 分钟后再来尝试!');
        }
        $conf = getConfig('admin', 'sys_pay');
        // 支付类型
        $param = input('post.');

        $type = $param['type'];
        // 商品类型 1软件(默认) 2会员
        // $goodType = $_POST['good_type'];
        //商品ID
        $goodId = $param['id'];

        if (preg_match('/^ali/', $type)) {
            $type = 'alipay';
        } else {
            $type = 'wechat';
        }
        if (!$conf[$type]) {
            $this->log(0, '当前支付模式已关闭,请选择其他支付');
            throw new Exception('当前支付模式已关闭,请选择其他支付');
        }
        $goodData = ScoreShop::find($goodId);
        if (!$goodData) {
            $this->log(0, '积分项目不存在');
            throw new Exception('积分项目不存在');
        }
        $param = [
            'good_id' => $goodId,
            'user_id' => $uid,
            'type' => $type,
            'name' => '积分充值' . $goodData['score'],
            'good_type' => 1,
            'money' => $goodData['money']
        ];
        if ($type == 'wechat') {
            if ($conf['wechat_method'] == '1') {
                $param['type'] = 'wxpay';
                // 易支付
                return (new Epay())->EpayCreateOrder($param);
            }
            // 其他支付
        } else if ($type == 'alipay') {
            if ($conf['alipay_method'] == '1') {
                // 易支付
                return (new Epay())->EpayCreateOrder($param);
            } else if ($conf['alipay_method'] == '2') {
                // 面对面
                // return (new Alipay())->initCreadeOrder($param);

            }
            // 其他
        }
    }
    // 奖励回调
    public function callReward($order = [])
    {
        // 订单邮箱发送
        // $this->orderNotify($order);
        Db::startTrans();
        try {
            Db::name('order')->where('out_trade_no', $order['out_trade_no'])->update(['status' =>  1, 'trade_no' => $order['trade_no']]);
            $goodId = $order['good_id'];
            $userId = $order['user_id'];
            $user = User::find($userId);
            $scoreShop = ScoreShop::find($goodId);
            if ($order['good_type'] == 1) {
                //    积分充值 默认
                $user->score += $scoreShop->score;
                $res = $user->save();
            } else {
                // 会员(待开发)
            }
            if ($res) {
                $this->log(1);
            }
            return $res;
        } catch (Exception $e) {
            Log::warning('支付奖励回调失败:' . $e->getMessage());
            $this->log(0,'支付奖励回调失败:' . $e->getMessage());
            Db::rollback();
            return false;
        }
    }
    /***
     * @订单通知
     *  */
    public function orderNotify($order)
    {
        $out_trade_no = $order['out_trade_no'];
        $price = $order['money'] ?? 0;
        $time = $order['create_time'] ?? 0;
        $data = Order::getStatistic();
        $data = [
            'order_no'           => $out_trade_no,
            'amount'             => $price,
            'pay_time'           => $time,
            'today_total'        => $data['today']['total'],
            'today_count'        => $data['today']['count'],
            'month_total'        => $data['month']['total'],
            'month_count'        => $data['month']['count'],
            'last_month_total'   => $data['last_month']['total'],
            'last_month_count'   => $data['last_month']['count'],
            'total'              => $data['total']['total'],
            'total_count'        => $data['total']['count'],
        ];
        // 发送邮件
        /* try {
            $mail = new Mail();
            $mail->to($mail->receiveMail)
                ->subject("【系统通知】新订单 {$data['order_no']} - {$data['amount']}元")
                ->content(view('pay/orderNotify', $data)->getContent())
                ->send();
        } catch (\Exception $e) {
            Log::error("订单邮件发送失败：" . $e->getMessage());
        } */
    }
    public function notifyUrl()
    {
        $outTradeNo = input('out_trade_no', '');
        $order = Order::where('out_trade_no', $outTradeNo)->find();
        if ($order) {
            $callType = $order['call_type'];
            if ($callType == 1) {
                if ((new Epay())->EpaynotifyUrl()) {
                    echo 'success';
                    exit();
                }
            } else if ($callType == 2) {
                /*  if ((new Alipay())->verifyNotify()) {
                    echo 'success';
                    exit();
                } */
            }
            echo 'fail';
            exit();
        }
    }
    public function returnUrl()
    {
        return (new Epay())->EpayReturnUrl();
    }
}
